<?php
/**
 * @class pages News module
 * @author Bethrezen <admin@devgroup.ru>
 * @desc Handles all pages related stuff.
 */
class pages
{
	var $core;
	
	var $tableName = 't_pages';
	
	var $action='';
	
	var $cur_page = 1;
	var $total_pages = 1;
	var $limit = 10;
	
	//! Constructor
	function pages(&$_core)
	{
		
		
		$this->core = $_core;
		
		$this->core->adminLinks['pages'] = 'Страницы';
		
		if (!file_exists(DB_DIR . $this->core->config->dbName . "/" . $this->tableName . ".txt"))
		{
		
			$SQL = "CREATE TABLE " . $this->tableName . " ( id inc , title str , content str , keywords str , url str )";
			
			$this->core->db->executeQuery($SQL);
			
			$this->core->db->executeQuery("INSERT INTO " . $this->tableName . " ( title , content , keywords ,  url ) VALUES ( 'Съешь же ещё этих мягких французских булок, да выпей чаю' , 'Это тестовая страница' , 'страница, тест, FCore' , '" .  $this->core->translitUrl('Съешь же ещё этих мягких французских булок, да выпей чаю') . "' )");
		}
		
		$action = 'main';
		if (isset($_GET['actionPages']))
			$action = $_GET['actionPages'];
		if (isset($_POST['actionPages']))
			$action = $_POST['actionPages'];
				
		$this->action = $action;
		
	}
	
	//! Shows list of pages
	function getPages($_limit = 10)
	{
		$this->limit = $_limit;
		$record = array();
		$up = 0;
		$this->cur_page = 1;
		if (isset($_GET['p'])==true)
		{
			$this->cur_page = intval($_GET['p']);
			$up = ($this->cur_page-1)*$this->limit;
		
		}
		$q4pages = $this->core->db->executeQuery("SELECT * FROM " . $this->tableName . " ORDER BY title LIMIT $up," . $this->limit);
		if ($q4pages->getRowCount() != 0)
		{
			while ($q4pages->next())
			
				$record[] = $q4pages->getCurrentValuesAsHash();
			
		}
	
		return ($record);
	}
	
	//! Paginator array
	function getPaginator()
	{
		$paginator = array();
		$q4paginator = $this->core->db->executeQuery("SELECT * FROM " . $this->tableName);
		$this->total_pages = ceil($q4paginator->getRowCount() / $this->limit);
		
		$paginator = range(1,$this->total_pages);
		
		return $paginator;
	}
	
	
	function makeListUrl($p)
	{
		if ($this->core->config->useModRewrite)
		{
		
			return $this->core->getDirectoryName() . "/pages/" . $p . ".html";
		}
		else
		{
		
			return basename($_SERVER['SCRIPT_NAME']) . "?action=pages&actionPages=list&p=".$p;
		}
	}
	
	//! Returns random pages
	function getRandomPages($num)
	{
		$record = array();
		
		$q4pages = $this->core->db->executeQuery("SELECT * FROM " . $this->tableName);
		if ($q4pages->getRowCount() != 0)
		{
			while ($q4pages->next())
			
				$record[] = $q4pages->getCurrentValuesAsHash();
			
		}
		$return = array();
		if ($num>$q4pages->getRowCount())
			$num = $q4pages->getRowCount();
			
		for ($i=0;$i<$num;$i++)
		{
			$r = $record[rand(0,count($record)-1)];
			if (!in_array($r, $return))
				$return[] = $r;
			else
				$num++;
		}
		return ($return);
	}
	
	function makeShowUrl($data)
	{
		if ($this->core->config->useModRewrite)
		{
		
			return $this->core->getDirectoryName() . "/page/" . $data['url'] . ".html";
		}
		else
		{
		
			return basename($_SERVER['SCRIPT_NAME']) . "?action=pages&actionPages=show&p=".$data['url'];
		}
	}
		
	/**
	 * Returns the page.
	 *
	 */
	function getPage($p)
	{
		$record = null;
		$q4pages = $this->core->db->executeQuery("SELECT * FROM " . $this->tableName . " WHERE url='".urlencode($p)."'");
		if ($q4pages->getRowCount() != 0)
		{
			$q4pages->next();
			
				$record = $q4pages->getCurrentValuesAsHash();
			
			
			
		}
		
		return ($record);
	}
	
	/**
	 * Mian admin action
	 *
	 */
	function admin()
	{
		
		$actFunc = "admin" . $this->action;
		$this->$actFunc();
	}
	
	function adminMain()
	{	
		
		$q4pages = $this->core->db->executeQuery("SELECT * FROM " . $this->tableName . " ORDER BY title ASC  ");
		if ($q4pages->getRowCount() != 0)
		{
			?>
			<h2>Страницы</h2>
			<table cellpadding="0" cellspacing="2" border="0"><TR><td>Заголовок</td><td>Действия</td></TR>
			
			<?php
		
			while ($q4pages->next())
			{
				$record = $q4pages->getCurrentValuesAsHash();
				?>
				<tr><TD><?=$record['title'];?></TD><TD><a href="<?=basename($_SERVER['SCRIPT_FILENAME']);?>?actAdmin=pages&actionPages=Edit&id=<?=$record['id']?>">Редактировать</a> <a href="<?=basename($_SERVER['SCRIPT_FILENAME']);?>?actAdmin=pages&actionPages=Remove&id=<?=$record['id']?>">Удалить</a></TD></tr>
				<?php
			}	
				
			?>
			</table>
			<a href="<?=basename($_SERVER['SCRIPT_FILENAME']);?>?actAdmin=pages&actionPages=Add">Добавить</a>
			<?php
		}
		
	}
	
	function adminRemove()
	{
		if (isset($_GET['id']))
		{
			$SQL = "DELETE FROM " . $this->tableName . " WHERE  id   = '" . intval($_GET['id']) . "' ";
			
				$this->core->db->executeQuery($SQL);
		}
		
		$this->adminMain();
	}
	
	function adminEdit()
	{
		if (isset($_GET['id']))
		{
			$q4edit = $this->core->db->executeQuery("SELECT * FROM " . $this->tableName . " WHERE id = '" . intval($_GET['id']) . "'");
			if ($q4edit->getRowCount() != 0)
			{
				$q4edit->next();
				$record = $q4edit->getCurrentValuesAsHash();
				?>
				<h2>Редактировать страницу</h2>
		<form action="<?=basename($_SERVER['SCRIPT_FILENAME']);?>" method="POST">
		<input type="hidden" name="actAdmin" value="pages">
		<input type="hidden" name="actionPages" value="Edit">
		<input type="hidden" name="id" value="<?=$record['id'];?>">
		<table cellspacing="2" cellpadding="0" border="0">
		<TR><TD>Заголовок:</TD><TD><input type="text" name="title" value="<?=$record['title'];?>"></TD></TR>
		<TR><TD>Ключевые слова:</TD><TD><input type="text" name="keywords" value="<?=$record['keywords'];?>"></TD></TR>
		<TR><TD>Текст:</TD><TD><textarea name="content"><?=$record['content'];?></textarea></TD></TR>
		<TR><TD>URL:</TD><TD><input type="text" name="url" value="<?=$record['url'];?>"> (пусто для автоматической транслитеризации)</TD></TR>
		<TR><TD>Редактирование:</TD><TD><input type="submit" value="Сохранить"></TD></TR>
		</table>
		</form><br />
		<a href="<?=basename($_SERVER['SCRIPT_FILENAME']);?>?actAdmin=pages">Назад в страницы</a>
				<?php
			
			}
			
		}
		if (isset($_POST['id']))
		{
			$title = addslashes($_POST['title']);
			$content = addslashes($_POST['content']);
			$keywords = (isset($_POST['keywords'])?addslashes($_POST['keywords']):'');
			$url = $this->core->translitUrl($title);
			if (isset($_POST['url']))
				if (!empty($_POST['url']))
					$url = $_POST['url'];
					
			$SQL = "UPDATE " . $this->tableName . " SET title='$title' , keywords='$keywords', content='$content' , url='" .  $url . "' WHERE id='" . intval($_POST['id']) . "'";
			$this->core->db->executeQuery($SQL);
			
			$this->adminMain();
		}
	}
	
	function adminAdd()
	{
		if (!isset($_POST['actAdmin']))
		{
		?>
		<h2>Добавить новость</h2>
		<form action="<?=basename($_SERVER['SCRIPT_FILENAME']);?>" method="POST">
		<input type="hidden" name="actAdmin" value="pages">
		<input type="hidden" name="actionPages" value="Add">
		<table cellspacing="2" cellpadding="0" border="0">
		<TR><TD>Заголовок:</TD><TD><input type="text" name="title" value=""></TD></TR>
		<TR><TD>Ключевые слова:</TD><TD><input type="text" name="keywords" value=""></TD></TR>
		<TR><TD>Текст:</TD><TD><textarea name="content"></textarea></TD></TR>
		<TR><TD>URL:</TD><TD><input type="text" name="url" value=""> (пусто для автоматической транслитеризации)</TD></TR>
		<TR><TD>Добавить:</TD><TD><input type="submit" value="Сохранить"></TD></TR>
		</table>
		</form><br />
		<a href="<?=basename($_SERVER['SCRIPT_FILENAME']);?>?actAdmin=pages">Назад в страницы</a>
		<?php
		}
		else
		{
			if (isset($_POST['title'],$_POST['content']))
			{
				$title = addslashes($_POST['title']);
				$content = addslashes($_POST['content']);
				$keywords = (isset($_POST['keywords'])?addslashes($_POST['keywords']):'');
				$url = $this->core->translitUrl($title);
				if (isset($_POST['url']))
					if (!empty($_POST['url']))
						$url = $_POST['url'];
						
				$SQL = "INSERT INTO " . $this->tableName . " ( title , content , keywords , url ) VALUES ( '$title' , '$content' , '$keywords' , '" .  $url . "' )";
				$this->core->db->executeQuery($SQL);
				
				$this->adminMain();
			}
			else
			{
				echo ("Ошибка.");
			}
			
		}
	}
}
